# plugs/dns.py
#
# $Id: dns.py 539 2006-04-02 16:23:47Z bart $

""" get hostname for ip or vice versa """

__copyright__ = 'this file is in the public domain'

from gozerbot.commands import cmnds
from gozerbot.examples import examples 
from gozerbot.plughelp import plughelp
import socket

plughelp.add('dns', 'do ip or host lookup')

def handle_hostname(bot, ievent):
    """ hostname <ipnr> .. get hostname of ip number"""
    try:
        item = ievent.args[0]
    except IndexError:
        ievent.missing('<ipnr>')
        return
    try:
        hostname = socket.gethostbyaddr(item)
        ievent.reply(hostname[0])
    except:
        ievent.reply("can't match " + str(item))

cmnds.add('host', handle_hostname, 'USER')
examples.add('host', 'get hostname for ip', 'host 194.109.129.219')

def handle_ip(bot, ievent):
    """ ip <hostname> .. get ip of hostname """
    try:
        item = ievent.args[0]
    except IndexError:
        ievent.missing('<hostname>')
        return
    try:
        ipnr = socket.gethostbyname(item)
        ievent.reply(ipnr)
    except:
        ievent.reply("can't match " + str(item))

cmnds.add('ip', handle_ip, 'USER')
examples.add('ip', 'show ip number of host', 'ip irc.xs4all.nl')

def handle_dns(bot, ievent):
    """ dns <hostname|ipnr> .. find dns entry for hostname or ipnr """
    if ievent.txt.count('.') > 2 or ievent.txt.count(':') > 2:
        handle_hostname(bot, ievent)
    else:
        handle_ip(bot, ievent)

cmnds.add('dns', handle_dns, 'USER')
examples.add('dns', 'dns <hostname|ipnr> .. find dns entry for hostname or \
ipnr', '1) dns r8.cg.nu 2) dns 127.0.0.1')
